package com.captain.leetcode2.链表;

import com.captain.leetcode.链表.ListNode;

import java.util.List;

/**
 * Des:
 * 输入：head = [1,2,3,4,5], n = 2
 * 输出：[1,2,3,5]
 * <p>
 * 输入：head = [1], n = 1
 * 输出：[]
 * <p>
 * 输入：head = [1,2], n = 1
 * 输出：[1]
 *
 * @author XL
 * @Date 2021/8/30 13:36
 */
public class 删除链表的倒数第N个结点19 {
    public static void main(String[] args) {
        ListNode node = new 删除链表的倒数第N个结点19().removeNthFromEnd(ListNode.getInstance(), 2);
        System.out.println(node);
    }

    //1 2 3 4 5   4   5 -3
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) return null;
        ListNode dummy = head;
        ListNode res = head;
        int len = 0;
        while (dummy != null) {
            dummy = dummy.next;
            len++;
        }
        if (n > len) return null;
        if (n == len) return head.next;
        int t = 1;
        while (res.next != null) {
            //找到节点
            if (len - t == n) {
                res.next = res.next.next;
                break;
            }
            t++;
            res = res.next;
        }
        return head;
    }
}
